import {Constant} from "../api/const";

const TokenKey = 'Token'

export default {
  getRangeMin: getRangeMin,
  getRangeMax: getRangeMax,
  getToken: getToken
}

export function getToken() {
  return localStorage.getItem('token')
}

//校验手机号格式
export function validateMobile(rule, value, callback) {
  const phoneRegex = /^[1][3-9]\d{9}$/;
  if (!value || phoneRegex.test(value)) {
    // 格式正确
    callback();
  } else {
    // 手机号格式不正确
    callback(new Error('手机号格式不正确'));
  }
}

//校验密码格式
export function validatePassword(rule, value, callback) {
  const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,16}$/;
  if (!value || passwordRegex.test(value)) {
    // 密码格式正确
    callback();
  } else {
    // 密码格式不正确
    callback(new Error('密码必须为8-16位字母和数字组合'));
  }
}

//校验身份证号格式
export function validateIdCard(rule, value, callback) {
  const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[01])\d{3}([0-9]|X)$/;
  if (!value || idCardRegex.test(value)) {
    callback();
  } else {
    callback(new Error('请输入有效的身份证号码'));
  }
}

//禁止选未来时间
export function disableFutureDates(time) {
  return time.getTime() > Date.now();
}

//限制开始时间不能晚于结束时间
export function handleStartDateChange(data, startDate, endDate) {
  if (data[endDate] && data[startDate] > data[endDate]) {
    data[endDate] = '';
  }
}

//限制结束时间不能早于开始时间
export function handleEndDateChange(data, startDate, endDate) {
  if (data[startDate] && data[endDate] < data[startDate]) {
    data[startDate] = '';
  }
}

//格式化金额
export function formatSalary(amount) {
  if (amount >= 10000) {
    let number = (amount / 10000).toFixed(1)
    return parseFloat(number) + '万';
  } else {
    let number = (amount / 1000).toFixed(1)
    return parseFloat(number) + '千';
  }
}

//隐藏手机号中间4位
export function hiddenPhoneNumber(phoneNumber) {
  if (phoneNumber && phoneNumber.length === 11) {
    return phoneNumber.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
  } else {
    return phoneNumber;
  }
}

//隐藏邮箱@前三位
export function hiddenEmail(email) {
  if (email && email.includes('@')) {
    const atIndex = email.indexOf('@');
    const prefix = email.substring(0, atIndex);
    const hiddenPrefix = prefix.substring(0, Math.min(3, prefix.length)).padEnd(prefix.length, '*');
    return hiddenPrefix + email.substring(atIndex);
  } else {
    return email;
  }
}

export function findNameByCode(array, code) {
  let obj = array.find(item => item.code === code)
  return obj.name
}

//下载文件
export function downloadFile(url, fileName) {
  const link = document.createElement('a');
  fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
    link.href = URL.createObjectURL(blob)
    link.download = fileName
    link.style.display = 'none';
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link);
  })
}

//0-10 10-20 30-
export function encodePositionRange(formItem) {
  let expRange = formItem.expRange
  let edu = formItem.edu
  if (expRange == -1) {
    expRange = '0'
  }
  if (edu == -1) {
    edu = ''
  }

  let salaryRange = formItem.salaryRange
  let expYearLower = getRangeMin(expRange)
  let expYearUpper = getRangeMax(expRange)
  let salaryLower = getRangeMin(salaryRange)
  let salaryUpper = getRangeMax(salaryRange)
  formItem.expYearLower = expYearLower
  formItem.expYearUpper = expYearUpper
  formItem.eduLevelLower = edu
  formItem.eduLevelUpper = edu
  formItem.salaryLower = salaryLower
  formItem.salaryUpper = salaryUpper
}

//0-10 10-20 30-
export function encodePersonRange(formItem) {
  let expRange = formItem.expRange
  let eduRange = formItem.eduRange
  let salaryRange = formItem.salaryRange
  let ageRange = formItem.ageRange
  let expYearLower = getRangeMin(expRange)
  let expYearUpper = getRangeMax(expRange)
  let salaryLower = getRangeMin(salaryRange)
  let salaryUpper = getRangeMax(salaryRange)
  let ageLower = getRangeMin(ageRange)
  let ageUpper = getRangeMax(ageRange)
  let eduLower = getRangeMin(eduRange)
  let eduUpper = getRangeMax(eduRange)
  formItem.expYearAmountLower = expYearLower
  formItem.expYearAmountUpper = expYearUpper
  formItem.eduLevelNumLower = eduLower
  formItem.eduLevelNumUpper = eduUpper
  formItem.salaryLower = salaryLower
  formItem.salaryUpper = salaryUpper
  formItem.ageLower = ageLower
  formItem.ageUpper = ageUpper
}

//0-10 10-20 30-
export function getRangeMin(rangeStr) {
  if (rangeStr == null || rangeStr == '') {
    return ''
  }
  const rangeArray = (rangeStr + '').split("-")
  let rangeMin = rangeArray[0]
  if (rangeMin == '') {
    return ''
  }
  return Number(rangeMin)
}

//0-10 10-20 30-
export function getRangeMax(rangeStr) {
  if (rangeStr == null || rangeStr == '') {
    return ''
  }
  const rangeArray = (rangeStr + '').split("-")
  let rangeMax = rangeArray[1]
  if (rangeMax == '') {
    return ''
  }
  return Number(rangeMax)
}

//0-10 10-20 30-
export function formatRange(min, max, unit) {
  let rs = min + '-' + max + unit
  if (!max) {
    rs = min + unit + '以上'
  }
  return rs
}

export function decodeAndSetPositionItem(item) {
  item.expRange = formatRangeValue(item.expYearLower, item.expYearUpper)
  item.salaryRange = formatRangeValue(formatSalary(item.salaryLower), formatSalary(item.salaryUpper))
  item.edu = item.eduLevelLower
}

export function decodePositionTagList(item) {
  let workCity = item.workCityName
  let expRange = formatRangeValue(item.expYearLower, item.expYearUpper)
  if (!item.expYearLower) {
    expRange = '经验不限'
  } else if (!item.expYearUpper) {
    expRange = item.expYearLower + '年以上'
  } else {
    expRange = expRange + '年'
  }
  let eduRange = Constant.eduLevelMap[item.eduLevelLower]
  let certName = ''
  if (item.certList && item.certList.length > 0) {
    certName = item.certList[0].name
  }
  let recruitmentAmount = item.recruitmentAmount
  if (recruitmentAmount) {
    recruitmentAmount = recruitmentAmount + '人'
  }

  item.expRange = expRange
  item.eduRange = eduRange

  return removeEmptyValue([workCity, expRange, eduRange, certName, recruitmentAmount])
}

export function decodeEntTagList(item) {
  decodeAndSetEntItem(item)
  return removeEmptyValue([item.majorName, item.natureName, item.sizeRange])
}

// 杭州 销售
// 客服
// 浙江工业大学 通信工程
export function decodeAndSetPersonItem(item) {
  let areaList = item.intentionAreaList
  let areaStr = array2str(areaList, 'name')
  let positionTypeList = item.intentionPositionTypeList
  let positionTypeStr = array2str(positionTypeList, 'name')
  let workList = item.workList
  let eduList = item.eduList
  let entName = ''
  let positionName = ''
  if (workList && workList.length > 0) {
    let work = workList[0]
    entName = work.entName
    positionName = work.positionName
  }
  let schoolName = ''
  let major = ''
  if (eduList && eduList.length > 0) {
    let edu = eduList[0]
    schoolName = edu.schoolName
    major = edu.major
  }
  item.formatIntentionCity = areaStr
  item.formatIntentionPosition = positionTypeStr
  item.entName = entName
  item.positionName = positionName
  item.schoolName = schoolName
  item.major = major
}

export function decodeAndSetEntItem(item) {
  item.natureName = Constant.entNatureMap[item.natureCode]
  item.sizeRange = formatRange(item.sizeMin, item.sizeMax, '人')
  let industryList = item.industryList
  if (industryList && industryList.length > 0) {
    item.majorName = industryList[0].industryName
  }
  item.logoUrl = item.logoUrl ? item.logoUrl : new URL('@/assets/images/common/ent-logo-default.png', import.meta.url).href
  item.recruiterAvatarUrl = item.recruiterAvatarUrl ? item.recruiterAvatarUrl : new URL('@/assets/images/common/ent-avatar-default.png', import.meta.url).href
}

export function array2str(array, propName) {
  if (array == null || array.length == 0) {
    return ''
  }
  let rs = ''
  array.forEach((item, index) => {
    let suffix = ''
    if (index < array.length - 1) {
      suffix = '、'
    }
    rs += item[propName] + suffix
  })
  return rs
}

export function formatRangeValue(min, max) {
  if (!min && !max) {
    return ''
  }
  let rs = min + '-' + max
  if (!max) {
    rs = min + '-'
  }
  return rs
}

export function formatUnit(value, unit) {
  if (value == null || value == '') {
    return ''
  }
  return value + unit
}

export function getEduLevelName(eduList) {
  if (eduList == null || eduList.length == 0) {
    return ''
  }
  let edu = eduList[0]
  if (!edu) {
    return ''
  }
  let level = edu.eduLevelNum
  return Constant.eduLevelMap[level]
}

export function getDutyLevelName(statusCode) {
  if (!statusCode) {
    return ''
  }
  let foundItem = null
  Constant.dutyStatusList.forEach((item) => {
    if (item.code == statusCode) {
      foundItem = item
    }
  })
  if (!foundItem) {
    return ''
  }
  return foundItem.leaveName
}

export function removeEmptyValue(array) {
  let rsArray = []
  array.forEach((item) => {
    if (item) {
      rsArray.push(item)
    }
  })

  return rsArray
}

export function formatHtml(str) {
  return str ? str.replace(/\n/g, '<br>') : ''
}

export function formatHtml2Text(str) {
  const regex = /<\/?.+?\/?>/gm;
  const subst = ``;

  let rs = str.replace(regex, subst);
  rs = rs.replace(/&nbsp;/ig, '');
  return rs
}

export function formatLocalStorageItem(str) {
  let rs = localStorage.getItem(str)
  if (rs && rs != 'null') {
    return rs
  } else {
    return ''
  }
}

export function formatNull(str) {
  if (str && str != 'null') {
    return str
  } else {
    return ''
  }
}

export function formatTime(seconds, type) {
  if (seconds && seconds != 'null') {
		const allHours = Math.floor(seconds / (60 * 60))
    const days = Math.floor(seconds / (24 * 60 * 60))
    const hours = Math.floor((seconds % (24 * 60 * 60)) / (60 * 60))
    const minutes = Math.floor((seconds % (60 * 60)) / 60);
    const remainingSeconds = seconds % 60;
    if (type == 'day') {
      return `${days}天${hours}小时`
    } else if (type == 'hour') {
      return `${allHours}小时`
    } else if (type == 'minute') {
      return `${allHours}小时 ${minutes}分钟`
    } else if (type == 'second') {
      return `${days}天 ${hours}小时 ${minutes}分钟 ${remainingSeconds}秒`
    }
  } else {
    return `0分钟`
  }
}

//计算某个日期距离今天有多少天
export function daysBetween(dateString) {
  if (!dateString) {
    return 0
  }
  const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
  const today = new Date(); // 获取今天的日期
  const inputDate = new Date(dateString); // 将输入的日期字符串转换为日期对象

  // 计算两日期之间的差异天数
  const differenceInDays = Math.round((inputDate - today) / oneDay);
  return differenceInDays + 1;
}

//判断某个时间是否晚于当前时间
export function isLaterThanNow(timeString) {
  const now = new Date(); // 获取当前时间
  const inputTime = new Date(timeString); // 将输入的时间字符串转换为日期对象

  // 判断输入的时间是否比当前时间晚
  return inputTime > now;
}
// 计算百分比
export function formatNumber(value, type = 1) {

  if (!value) {
    return 0
  }
  switch (type) {
    case 0:
      return Math.round(value);
    case 1:
      if (value.toFixed(1).endsWith('.0')) {
        return value.toFixed(1).slice(0, -2);
      }else{
        return value.toFixed(1);
      }
    case 2:
      return value.toFixed(2);
    default:
      throw new Error('Invalid type value. Must be 0, 1, or 2.');
  }
}
